<!-- 药品报销比例管理页面 -->
<template>
  <div class="rule-flex-center">
    <div class="rule-card rule-table-card">
      <div class="rule-title">药品报销比例列表</div>
      <div class="table-header">
        <el-button type="primary" @click="onAdd" class="add-btn" size="large">+ 新增</el-button>
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="loadData" class="status-filter">
          <el-option label="全部" value="" />
          <el-option label="启用" value="启用" />
          <el-option label="停用" value="停用" />
        </el-select>
      </div>
      
      <el-table :data="ratioList" class="rule-table" border v-loading="loading">
        <el-table-column prop="drugType" label="药品类型" align="center" width="120"/>
        <el-table-column prop="reimbursementRatio" label="报销比例(%)" align="center" width="140">
          <template #default="{ row }">
            {{ row.reimbursementRatio }}%
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'info'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" align="center" show-overflow-tooltip/>
        <el-table-column prop="updateTime" label="更新时间" align="center" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="onEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="rule-card rule-form-card">
      <div class="rule-title">
        {{ isEdit ? '编辑' : '新增' }}报销比例
        <span class="tip">药品类型不可重复</span>
      </div>
      
      <el-form 
        :model="form" 
        :rules="formRules"
        ref="formRef"
        label-width="100px" 
        class="rule-form"
      >
        <el-form-item label="药品类型" prop="drugType">
          <el-select v-model="form.drugType" placeholder="请选择药品类型" style="width: 100%;">
            <el-option label="甲类" value="甲类" />
            <el-option label="乙类" value="乙类" />
            <el-option label="丙类" value="丙类" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报销比例" prop="reimbursementRatio">
          <el-input-number 
            v-model="form.reimbursementRatio" 
            :min="0" 
            :max="100" 
            :precision="2"
            style="width: 100%;" 
            placeholder="请输入报销比例"
          />
          <div class="form-tip">范围：0-100%</div>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="停用">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="说明" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入说明信息" 
          />
        </el-form-item>
        
        <el-form-item>
          <div class="form-buttons">
            <div class="primary-buttons">
              <el-button type="primary" @click="onSave" class="form-btn" :loading="saveLoading">
                {{ isEdit ? '更新' : '保存' }}
              </el-button>
              <el-button @click="onReset" class="form-btn">重置</el-button>
            </div>
            <div v-if="isEdit" class="secondary-buttons">
              <el-button @click="onCancel" class="form-btn cancel-btn">取消编辑</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDrugRatioList, addDrugRatio, updateDrugRatio, deleteDrugRatio } from '@/api/drugRatio'

// 响应式数据
const ratioList = ref([])
const loading = ref(false)
const saveLoading = ref(false)
const statusFilter = ref('')
const isEdit = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  ratioId: null,
  drugType: '',
  reimbursementRatio: 0,
  status: '启用',
  description: ''
})

// 表单验证规则
const formRules = {
  drugType: [
    { required: true, message: '请选择药品类型', trigger: 'change' }
  ],
  reimbursementRatio: [
    { required: true, message: '请输入报销比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '报销比例范围为0-100', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    console.log('加载药品报销比例数据，状态筛选：', statusFilter.value)
    
    const response = await getDrugRatioList(statusFilter.value)
    console.log('药品报销比例响应：', response)
    
    if (response.flag && response.data) {
      ratioList.value = response.data
      ElMessage.success('数据加载成功')
    } else {
      ratioList.value = []
      ElMessage.warning(response.message || '数据加载失败')
    }
  } catch (error) {
    console.error('加载药品报销比例失败：', error)
    ElMessage.error('数据加载失败：' + error.message)
    ratioList.value = []
  } finally {
    loading.value = false
  }
}

// 新增操作
const onAdd = () => {
  isEdit.value = false
  resetForm()
}

// 编辑操作
const onEdit = (row) => {
  isEdit.value = true
  form.ratioId = row.ratioId
  form.drugType = row.drugType
  form.reimbursementRatio = row.reimbursementRatio
  form.status = row.status
  form.description = row.description || ''
  
  // 清除表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 保存操作
const onSave = async () => {
  try {
    // 表单验证
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return
    
    saveLoading.value = true
    
    // 检查药品类型是否重复（排除当前编辑的记录）
    const duplicate = ratioList.value.find(item => 
      item.drugType === form.drugType && 
      (!isEdit.value || item.ratioId !== form.ratioId)
    )
    
    if (duplicate) {
      ElMessage.warning(`药品类型"${form.drugType}"已存在，请选择其他类型`)
      return
    }
    
    // 准备提交数据
    const submitData = {
      drugType: form.drugType,
      reimbursementRatio: form.reimbursementRatio,
      status: form.status,
      description: form.description
    }
    
    if (isEdit.value) {
      submitData.ratioId = form.ratioId
    }
    
    console.log('提交数据：', submitData)
    
    // 调用API
    const response = isEdit.value 
      ? await updateDrugRatio(submitData)
      : await addDrugRatio(submitData)
    
    console.log('保存响应：', response)
    
    if (response.flag) {
      ElMessage.success(response.message || `${isEdit.value ? '更新' : '新增'}成功`)
      resetForm()
      loadData() // 重新加载数据
    } else {
      ElMessage.error(response.message || `${isEdit.value ? '更新' : '新增'}失败`)
    }
  } catch (error) {
    console.error('保存失败：', error)
    ElMessage.error('保存失败：' + error.message)
  } finally {
    saveLoading.value = false
  }
}

// 删除操作
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除药品类型"${row.drugType}"的报销比例吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('删除报销比例：', row.ratioId)
    const response = await deleteDrugRatio(row.ratioId)
    console.log('删除响应：', response)
    
    if (response.flag) {
      ElMessage.success(response.message || '删除成功')
      loadData() // 重新加载数据
      
      // 如果删除的是当前编辑的记录，重置表单
      if (isEdit.value && form.ratioId === row.ratioId) {
        resetForm()
      }
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 重置表单
const resetForm = () => {
  form.ratioId = null
  form.drugType = ''
  form.reimbursementRatio = 0
  form.status = '启用'
  form.description = ''
  isEdit.value = false
  
  // 清除表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 取消编辑
const onCancel = () => {
  resetForm()
}

// 重置按钮
const onReset = () => {
  if (isEdit.value) {
    // 编辑模式下重置为原始数据
    const original = ratioList.value.find(item => item.ratioId === form.ratioId)
    if (original) {
      onEdit(original)
    }
  } else {
    // 新增模式下清空表单
    resetForm()
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.rule-flex-center {
  display: flex;
  justify-content: stretch;
  align-items: flex-start;
  gap: 40px;
  min-height: 100vh;
  padding: 48px 40px 0 40px;
  background: #f7f8fa;
  width: 100%;
  box-sizing: border-box;
}

.rule-card {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  padding: 32px 36px 28px 36px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.rule-table-card {
  flex: 2;
  min-width: 0;
  margin-top: 0;
}

.rule-form-card {
  flex: 1;
  min-width: 400px;
  max-width: 500px;
  margin-top: 0;
}

.rule-title {
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 24px;
  color: #303133;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

.add-btn {
  font-size: 16px;
  border-radius: 6px;
  padding: 12px 24px;
}

.status-filter {
  width: 120px;
}

.rule-table {
  background: #fff;
  font-size: 14px;
}

.rule-table :deep(.el-table__cell) {
  min-height: 48px;
  height: 48px;
  line-height: 48px;
  font-size: 14px;
}

.rule-table :deep(.el-table__header-wrapper .el-table__header) {
  background-color: #fafafa;
}

.tip {
  color: #f56c6c;
  font-size: 14px;
  font-weight: normal;
  margin-left: 8px;
}

.rule-form {
  margin-top: 8px;
}

.form-btn {
  min-width: 80px;
  font-size: 14px;
  border-radius: 6px;
  margin-right: 12px;
}

.form-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.primary-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.secondary-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
}

.cancel-btn {
  color: #909399;
  border-color: #dcdfe6;
  margin-right: 0;
}

.cancel-btn:hover {
  color: #f56c6c;
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.2;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .rule-flex-center {
    flex-direction: column;
    gap: 20px;
    padding: 20px;
  }
  
  .rule-form-card {
    max-width: none;
    min-width: 0;
  }
}

@media (max-width: 768px) {
  .rule-flex-center {
    padding: 16px 12px;
  }
  
  .rule-card {
    padding: 20px 16px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .add-btn {
    width: 100%;
  }
  
  .status-filter {
    width: 100%;
  }
  
  .primary-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-btn {
    width: 100%;
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .secondary-buttons .form-btn {
    margin-bottom: 0;
  }
}
</style> 